
package com.neo.tiny.admin.service.sys.impl;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neo.tiny.admin.mapper.sys.SysDeptMapper;
import com.neo.tiny.admin.service.sys.SysDeptService;
import com.neo.tiny.admin.entity.sys.SysDept;
import com.neo.tiny.common.constant.ErrorCodeConstants;
import com.neo.tiny.common.exception.WebApiException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 部门
 *
 * @author yqz
 * @date 2022-08-15 23:18:24
 */
@Service
@AllArgsConstructor
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    private final SysDeptMapper deptMapper;

    @Override
    public List<Tree<Long>> listDeptTrees() {
        return this.getDeptTree(this.list(Wrappers.emptyWrapper()), 0L);
    }

    @Override
    public void validDepts(Collection<Long> ids) {
        Assert.notEmpty(ids, "待校验部门id集合不能为空");

        List<SysDept> deptList = deptMapper.selectBatchIds(ids);
        Map<Long, SysDept> deptMap = deptList.stream()
                .collect(Collectors.toMap(SysDept::getId, Function.identity(), (key1, key2) -> key1));

        ids.forEach(deptId -> {
            SysDept dept = deptMap.get(deptId);
            if (Objects.isNull(dept)) {
                throw new WebApiException(ErrorCodeConstants.DEPT_NOT_FOUND);
            }
        });
    }

    /**
     * 构建部门树
     *
     * @param depts    部门
     * @param parentId 父级id
     * @return
     */
    private List<Tree<Long>> getDeptTree(List<SysDept> depts, Long parentId) {
        List<TreeNode<Long>> collect = depts.stream().filter(dept -> dept.getId().intValue() != dept.getParentId())
                .sorted(Comparator.comparingInt(SysDept::getOrderNum)).map(dept -> {
                    TreeNode<Long> treeNode = new TreeNode();
                    treeNode.setId(dept.getId());
                    treeNode.setParentId(dept.getParentId());
                    treeNode.setName(dept.getDeptName());
                    treeNode.setWeight(dept.getOrderNum());
                    // 扩展属性
                    Map<String, Object> extra = new HashMap<>(4);
                    extra.put("createTime", dept.getCreateTime());
                    extra.put("leader", dept.getLeader());
                    treeNode.setExtra(extra);
                    return treeNode;
                }).collect(Collectors.toList());

        return TreeUtil.build(collect, parentId);
    }
}
